import json
import json

import music_tag
import requests
from DrissionPage import SessionPage
from flask import Flask, redirect
from flask_cors import cross_origin

app = Flask(__name__)
page = SessionPage()
headers = {
    'User-Agent': 'okhttp/5.0.0-alpha.11',
    'Connection': 'Keep-Alive'
}

def get(url):
    page.get(url, headers=headers)
    return page.json

def print_json(data):
    print(json.dumps(data, indent=2, ensure_ascii=False))

def convert_to_lrc(lyrics_list):
    lrc_lines = []
    for item in lyrics_list:
        time_in_seconds = float(item['time'])
        minutes = int(time_in_seconds // 60)
        seconds = time_in_seconds % 60
        timestamp = f"[{minutes:02d}:{seconds:05.2f}]"
        lrc_line = f"{timestamp} {item['lineLyric']}"
        lrc_lines.append(lrc_line)
    return '\n'.join(lrc_lines)

def update_metadata(file_path, title=None, album=None, artist=None, lyrics=None, cover_image_path=None):
    file = music_tag.load_file(file_path)
    if title:
        file['title'] = title
    if album:
        file['album'] = album
    if artist:
        file['artist'] = artist
    if lyrics:
        file['lyrics'] = lyrics
    if cover_image_path:
        with open(cover_image_path, 'rb') as img:
            file['artwork'] = img.read()
    file.save()

def get_br(data_string):
    entries = data_string.split(';')
    audio_streams = []
    for entry in entries:
        if entry.strip():
            info = entry.strip().split(',')
            stream_info = {
                "bitrate": int(info[1].split(':')[1]),
                "format": info[2].split(':')[1],
                "size": info[3].split(':')[1]
            }
            audio_streams.append(stream_info)
    return audio_streams

@app.route('/')
def home():
    # return '''
    # /s/关键词
    # /id/品质/后缀
    # /l/id/品质/后缀
    # '''
    return '''
    /页数/每页数量/关键词，
    如：/0/20/薛之谦
    '''
@app.route('/<pageNo>/<pageNum>/<key>')
@cross_origin(origins='http://localhost:8889', methods=['GET'])
def search(pageNo,pageNum,key):
    url = f"https://search.kuwo.cn/r.s?client=kt&pn={pageNo}&rn={pageNum}&all={key}&vipver=1&ft=music&encoding=utf8&rformat=json&mobi=1"
    search_results = get(url)['abslist']
    song_list = []
    for search in search_results:
        id =search['DC_TARGETID']
        url = f"http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId={id}"
        lrc = get(url)['data']
        lrc_content = lrc['lrclist']
        #lrc_content = convert_to_lrc(lrc['lrclist'])
        song_list.append( {
            'id':id,
            'name': search['NAME'],
            'artist': search['ARTIST'],
            'album': search['ALBUM'],
            'img':lrc['songinfo']['pic'].replace("240","2000"),
            'lrc':lrc_content
            # 'bitrates': get_br(search['MINFO'])
        })

    return json.dumps(song_list, indent=2, ensure_ascii=False)

@app.route('/<id>/<br1>/<br2>')
def get_download_url(id, br1,br2):
    target_url = f'https://mobi.kuwo.cn/mobi.s?f=web&prod=kwplayer_ar_10.3.3.0&type=convert_url&rid={id}&br={br1}k{br2}'
    rs = requests.get(target_url, headers=headers).text
    song_url = rs.split('\n')[2][4:]
    return redirect(song_url)


# print(search(0,20,'薛之谦'))
if __name__ == '__main__':
    app.run(debug=True,port=37808)
